package com.episode.duetapi.utils;

import java.security.Key;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.episode.duetapi.exceptionHandle.CustomerException;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;

public class JwtHelper {
	
	private static final Logger logger = LoggerFactory.getLogger(JwtHelper.class);


    private static String base64Security = "base64Security";
    private static long TTLMillis = 1000 * 60 * 60 * 24 * 30;//一个月

    private static String issuer = "episode"+System.currentTimeMillis();
    private static String audience = "admin$##";


    public static Claims parseJWT(String jsonWebToken) throws CustomerException {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(DatatypeConverter.parseBase64Binary(base64Security))
                    .parseClaimsJws(jsonWebToken).getBody();
            return claims;
        } catch (
                ExpiredJwtException e) {
            logger.error("Token已过期: {} " + e);
            throw new CustomerException(ResultCode.AUTHORIZATION4002);
        } catch (
                UnsupportedJwtException e) {
            logger.error("Token格式错误: {} " + e);
            throw new CustomerException(ResultCode.AUTHORIZATION4003);
        } catch (
                MalformedJwtException e) {
            logger.error("Token没有被正确构造: {} " + e);
            throw new CustomerException(ResultCode.AUTHORIZATION4004);
        } catch (
                SignatureException e) {
            logger.error("签名失败: {} " + e);
            throw new CustomerException(ResultCode.AUTHORIZATION4005);
        } catch (
                IllegalArgumentException e) {
            logger.error("非法参数异常: {} " + e);
            throw new CustomerException(ResultCode.AUTHORIZATION4006);
        }

    }

    public static String createJWT(int id, String name, int roleId) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("id", id)
                .claim("userName", name)
                .claim("roleId", roleId)
                .setIssuer(issuer)
                .setAudience(audience)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        return builder.compact();
    }
    
    public static void main(String[] args) {
    	String sign = createJWT(123,"25555",456);
    	System.out.println(sign);
	}

}
